package com.langshixiaobai.mqdemo.common;

import com.langshixiaobai.mqdemo.server.core.MSGQueue;

import java.io.*;

//序列化和反序列化操作
public class BinaryTool {
    //对象->二进制 序列化
    public static byte[] toBytes(Object object) {

        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
                objectOutputStream.writeObject(object);
            }
            //返回序列化后的二进制数组
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //二进制->对象 反序列化
    public static Object formBytes(byte[] bytes){
        Object object = null;
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
                 object = objectInputStream.readObject();

                return object;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return object;
    }


}
